package com.wzcl.app.controller.student;

import com.wzcl.app.dao.model.AppUser;
import com.wzcl.app.dao.model.Commodity;
import com.wzcl.app.dao.model.Orders;
import com.wzcl.app.dao.model.UserCourse;
import com.wzcl.app.dao.repository.*;
import com.wzcl.app.model.common.MyPage;
import com.wzcl.app.model.common.RVO;
import com.wzcl.app.model.dto.OrdersDto;
import com.wzcl.app.model.vo.OrderVo;
import com.wzcl.app.service.OrderService;
import com.wzcl.app.utils.DateUtil;
import com.wzcl.app.utils.RequestUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import net.minidev.json.JSONUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

@Log4j2
@RestController
@RequestMapping("/userOrder")
@Api(value = "用户订单管理controller", tags = {"用户订单管理接口"})
public class UserOrderController {

    @Resource
    private OrderService orderService;
    @Resource
    private AppUserRepository appUserRepository;
    @Resource
    private CommodityRepository commodityRepository;
    @Resource
    private CourseRepository courseRepository;
    @Resource
    private UserCourseRepository userCourseRepository;
    @Resource
    private OrdersRepository ordersRepository;

    @ApiOperation("拉起订单")
    @PostMapping("/create")
    public RVO<OrderVo> createOrder(@RequestBody @Valid OrdersDto orderDto){
        System.out.println("拉起订单");
        orderDto.setUserPhone(SecurityContextHolder.getContext().getAuthentication().getName());
        Orders order = orderService.addOrder(orderDto);
        return RVO.success(OrderVo.create(order));
    }

    @ApiOperation("即刻拉起订单")
    @PostMapping("/createEager")
    public RVO createEagerOrder(@RequestBody OrdersDto orderDto){
        String phone = SecurityContextHolder.getContext().getAuthentication().getName();
        orderDto.setUserPhone(phone);
        Orders order = orderService.addOrderEager(orderDto);
        //判断是不是0元免费课程如果是就直接添加到用户课程表
        //TODO 这种改法很垃圾 实属无奈之举 可以优化一下
        if (order.getPayMoney().doubleValue() == 0){
            UserCourse userCourse = new UserCourse();
            userCourse.setCreateTime(DateUtil.getDateBySystemTime(System.currentTimeMillis()));
            userCourse.setUserId(appUserRepository.findByPhone(phone).getId());
            userCourse.setUserPhone(phone);
            Commodity commodity = commodityRepository.findAllById(orderDto.getCommodityId());
            userCourse.setCourse(courseRepository.findAllByCourseId(commodity.getResourceId()));
            userCourseRepository.save(userCourse);
            //改变订单状态
            ordersRepository.setPayStateAndOrdersStateByNo(1, 3, 3, order.getNo());
            return RVO.success("0元课程购买成功", 202);
        }
        OrderVo orderVo = OrderVo.create(order);
        return RVO.success(orderVo);
    }

    @ApiOperation("取消订单")
    @PostMapping("/cancel")
    public RVO<OrderVo> cancelOrder(@RequestBody OrdersDto ordersDto){
        Orders order = orderService.delOrderById(ordersDto.getId());
        return RVO.success(OrderVo.create(order));
    }

    @ApiOperation("修改地址")
    @PostMapping("/update")
    public RVO<OrderVo> updateOrder(@RequestBody OrdersDto ordersDto){
        Orders order = orderService.updateOrder(ordersDto);
        return RVO.success(OrderVo.create(order));
    }

    @ApiOperation("查询订单是否支付")
    @GetMapping("/isPay")
    public RVO getOrderPayStatus(@RequestParam String orderNumber){
        return RVO.success(orderService.getOrderPayStatus(orderNumber));
    }

    @ApiOperation("获取订单")
    @PostMapping("/get")
    public RVO<OrderVo> getOrder(@RequestBody OrdersDto ordersDto){
        Orders order = orderService.getOrderById(ordersDto.getId());
        if(order != null && order.getUserPhone().equals(SecurityContextHolder.getContext().getAuthentication().getName())) {
            return RVO.success(OrderVo.create(order));
        }
        return RVO.success(null);
    }

    @PostMapping("/getList")
    @ApiOperation("订单列表List")
    public RVO<List<OrderVo>> getOrderList(@RequestBody OrdersDto orderDto){
        orderDto.setUserPhone(SecurityContextHolder.getContext().getAuthentication().getName());
        List<Orders> list = orderService.getOrderList(orderDto);
        if(list != null && list.size() > 0){
            return RVO.success(list.stream().map(OrderVo::create).collect(Collectors.toList()));
        }
        return RVO.success(null);
    }

    @PostMapping("/getPage")
    @ApiOperation("订单列表Page")
    public RVO<List<OrderVo>> getOrderPage(@RequestBody OrdersDto orderDto) throws NoSuchMethodException {
        orderDto.setUserPhone(SecurityContextHolder.getContext().getAuthentication().getName());
        MyPage<Orders> page = orderService.getOrderPage(orderDto);
        if(page != null && page.getContent().size() > 0){
            return RVO.success(page.getContent().stream().map(OrderVo::create).collect(Collectors.toList()),page);
        }
        return RVO.success(null);
    }

    @ApiOperation("拉起支付")
    @PostMapping("/pay")
    public RVO<String> pay(@RequestBody OrdersDto ordersDto, HttpServletRequest request){
        ordersDto.setIp(RequestUtil.getIpAddress(request));
        String body = orderService.payOrder(ordersDto);
        System.out.println("支付响应体："+body);
        return RVO.success(body);
    }
}
